import { system, ChatSendBeforeEvent } from "@minecraft/server"
import { showMainGui } from '../ui/MainUi'
import { showMainLandUI, showLandListUI } from '../ui/LandUi'
import { receive_land } from '../utils/Land';
import { LandList } from '../core/data/land/LandList'
import { getTPS } from "../utils/Game"

const land_list = new LandList()

/**
* @param { ChatSendBeforeEvent } event
*/
function run_commands(event) {
    var player = event.sender;
    var message = event.message;

    /**
     * 命令处理函数集合
     * @type { {[key: string]: {func: Function, child: {[key: string]: {func: Function}} } }
     */
    const commands = {
        "menu": {
            func: () => showMainGui(player)
        },
        "land": {
            // 子命令处理
            child: {
                "auto": {
                    func: () => receive_land(player, land_list)
                },
                "list": {
                    func: () => showLandListUI(player)
                },
                "help": {
                    func: () => {
                        player.sendMessage([
                            "§2--- 命令-领地帮助 ---§r",
                            "§l!land 打开领地菜单",
                            "§l!land auto 领取新领地",
                            "§l!land list 打开领地列表菜单",
                            "§l!land help 获取领地命令帮助"
                        ].join("\n"));
                    }
                }
            },
            // 默认命令处理（当无子命令时执行）
            func: () => showMainLandUI(player)
        },
        "tps": {
            func: () => {
                player.sendMessage([
                    "当前 TPS 为: §b" + getTPS()
                ].join("\n"))
            }
        },
        "help": {
            func: () => {
                player.sendMessage([
                    "§2--- 命令帮助 ---§r",
                    "§l!menu 打开菜单",
                    "§l!land 打开领地菜单",
                    "§l!land help 获取领地命令帮助",
                    "§l!tps 获取当前游戏 TPS",
                    "§l!help 获取领地命令帮助"
                ].join("\n"));
            }
        }
    }

    event.cancel = true;
    const commandStr = message.slice(1).trim(); // 移除感叹号
    const parts = commandStr.split(/\s+/); // 分割命令参数
    const baseCmd = parts[0].toLowerCase(); // 主命令

    // 查找命令树中的对应函数
    const findCommandHandler = (cmdTree, path) => {
        if (path.length === 0 && cmdTree.func) {
            return cmdTree.func; // 找到最终函数
        }

        const nextToken = path[0].toLowerCase();
        if (cmdTree.child && cmdTree.child[nextToken]) {
            return findCommandHandler(cmdTree.child[nextToken], path.slice(1));
        }

        // 当前层级处理（带参数的场景）
        if (cmdTree.func) {
            return () => cmdTree.func(path);
        }

        return null;
    }

    const commandPath = parts.slice(1); // 剩余命令参数
    const handler = findCommandHandler(commands[baseCmd] || {}, commandPath);

    system.run(() => {
        if (commands[baseCmd]) {
            handler ? handler() : player.sendMessage("§c命令参数错误! 使用/land查看帮助");
        } else {
            player.sendMessage("§c未知命令! 可用命令: !menu, !land");
        }
    });
}

export {
    run_commands
}